package com.panghl.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.panghl.entity.PaymentInfo;
import com.panghl.enums.PayType;
import com.panghl.mapper.PaymentInfoMapper;
import com.panghl.service.PaymentInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Map;

@Service
@Slf4j
public class PaymentInfoServiceImpl extends ServiceImpl<PaymentInfoMapper, PaymentInfo> implements PaymentInfoService {

    @Override
    public void createPaymentInfo(Map<String, Object> plaintTextMap) {
        log.info("记录支付日志");
        // 订单号
        String orderNo = (String)plaintTextMap.get("out_trade_no");
        // 微信支付订单号
        String transactionId = (String) plaintTextMap.get("transaction_id");
        // 支付类型
        String tradeType = (String) plaintTextMap.get("trade_type");
        // 交易状态
        String tradeState = (String) plaintTextMap.get("trade_state");
        //订单金额
        Map<String,Object> amountMap = (Map) plaintTextMap.get("amount");
        Integer total = ((Double)amountMap.get("total")).intValue();

        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(orderNo);
        paymentInfo.setPaymentType(PayType.WXPAY.getType());
        paymentInfo.setTransactionId(transactionId);
        paymentInfo.setTradeType(tradeType);
        paymentInfo.setTradeState(tradeState);
        paymentInfo.setPayerTotal(total);
        paymentInfo.setContent(new Gson().toJson(plaintTextMap));
        baseMapper.insert(paymentInfo);
    }

    /**
     * 记录支付日志，支付宝
     * @param params
     */
    @Override
    public void createPaymentInfoForAliPay(Map<String, String> params) {
        log.info("记录支付日志");
        // 获取订单号
        String out_trade_no = params.get("out_trade_no");
        // 业务编号
        String trade_no = params.get("trade_no");
        // 交易状态
        String trade_status = params.get("trade_status");
        String total_amount = params.get("total_amount");
        int totalAmountInt = new BigDecimal(total_amount).multiply(BigDecimal.valueOf(100)).intValue();
        PaymentInfo paymentInfo = new PaymentInfo();
        paymentInfo.setOrderNo(out_trade_no);
        paymentInfo.setPaymentType(PayType.ALIPAY.getType());
        paymentInfo.setTransactionId(trade_no);
        paymentInfo.setTradeType("电脑网站支付");
        paymentInfo.setTradeState(trade_status);
        paymentInfo.setPayerTotal(totalAmountInt);
        paymentInfo.setContent(JSONObject.toJSONString(params));
    }
}
